package baiwa.rta.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;

/**
 *
 * @author jirapatj
 */
public class CommonUtils {

    public static List<String> splitWithEmtryValue(String input, final String SEPARATOR) {
        List<String> list = new ArrayList<String>();
        StringTokenizer st = new StringTokenizer(input, SEPARATOR, true);
        boolean lastElementIsSeparator = true;
        while (st.hasMoreElements()) {
            String s = st.nextToken();

            if (!s.equals(SEPARATOR)) {
                list.add(s);
                lastElementIsSeparator = false;
            } else {
                if (lastElementIsSeparator) {
                    list.add("");
                }
                lastElementIsSeparator = true;
            }
        }
        if (lastElementIsSeparator) {
            list.add("");
        }

        return list;
    }

    public static boolean isNumber(String numberString) {
        if (isNullOrEmtry(numberString)) {
            return false;
        }
        try {
            NumberFormat.getInstance().parse(numberString);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    public static boolean isBoolean(String input) {
        return input.equalsIgnoreCase("true") || input.equalsIgnoreCase("false") ? true : false;
    }

    public static void displayArray(Object[] objs) {
        for (Object obj : objs) {
            System.out.println(obj);
        }
    }

    public static void displayArray(Collection<?> collection) {
        displayArray(collection.toArray());
    }

    public static Number parseNumber(String input) throws ParseException {
        if (CommonUtils.isNullOrEmtry(input)) {
            return 0;
        }

        // check can parse number
        Number number = NumberFormat.getInstance().parse(input);

        if (input.contains("F")) {
            try {
                return number.floatValue();
            } catch (Exception e) {
            }
        } else if (input.contains("D")) {
            try {
                return number.doubleValue();
            } catch (Exception e) {
            }
        } else if (input.contains("L")) {
            try {
                return number.longValue();
            } catch (Exception e) {
            }
        }

        return number.intValue();
    }

    public static String[] splitString(String src, int length) {
        if (src == null) {
            src = "";
        }

        List<String> results = new ArrayList<String>();

        int srcLength = src.length();

        for (int beginIndex = 0; beginIndex < srcLength; beginIndex += length) {
            int endIndex = beginIndex + length;
            if (endIndex > srcLength) {
                endIndex = srcLength;
            }
            results.add(src.substring(beginIndex, endIndex));
        }

        return results.toArray(new String[0]);
    }

    public static boolean isNotNullAndEqual(String input1, String input2) {
        return CommonUtils.isNullOrEmtry(input1, input2) ? input1.equals(input2) : false;
    }

    public static boolean isNullOrEmtry(Object... inputs) {
        if (inputs == null) {
            return true;
        }

        for (Object obj : inputs) {
            if (CommonUtils.isNullOrEmtry(obj)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isNullOrEmtry(Object input) {
        if (input == null) {
            return true;
        }
        if (input instanceof Boolean) {
            return (Boolean) input;
        }
        if (input instanceof String) {
            return ((String) input).trim().equals("");
        }
        if (input instanceof Collection<?>) {
            return ((Collection<?>) input).isEmpty();
        }
        return false;
    }

    public static void print(Object object) {

        if (object instanceof Object[]) {
            Object[] objs = (Object[]) object;
            for (Object i : objs) {
                System.out.println(i);
            }
        } else if (object instanceof Collection) {
            Collection collection = (Collection) object;
            for (Object i : collection) {
                System.out.println(i);
            }
        } else {
            System.out.println(object);
        }
    }

    public static Object copy(Object object) throws Throwable {
        ByteArrayOutputStream baostream = new ByteArrayOutputStream();
        ObjectOutputStream oostream = new ObjectOutputStream(baostream);
        oostream.writeObject(object);
        oostream.flush();
        oostream.close();
        ByteArrayInputStream baistream = new ByteArrayInputStream(baostream.toByteArray());
        ObjectInputStream oistream = new ObjectInputStream(baistream);
        Object copy = oistream.readObject();
        oistream.close();
        return copy;
    }

    public static boolean isDeleteFileFolder(File directory) {
        boolean flag = false;
        if (!directory.exists()) {
            flag = false;
        }
        File[] file = directory.listFiles();
        for (File f : file) {
            System.out.println(f.getName());
            if (f.delete()) {
                //Delete file
                flag = true;
            }
        }
        if (flag) {
            //Delete folder
            directory.delete();
        }
        return flag;
    }

    public static void CopyFile(File in, File out) throws Exception {
        FileInputStream fis = new FileInputStream(in);
        FileOutputStream fos = new FileOutputStream(out);
        byte[] buf = new byte[1024];
        int i = 0;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
        fis.close();
        fos.close();
    }

    public static void main(String[] args) throws Exception {
        System.out.println(getHtmlString("http://kaohoon.com"));
    }

    public static String getHtmlString(String path) throws IOException {
        URL url = new URL(path);
        url.openConnection();

        InputStream in = null;
        InputStreamReader reader = null;
        BufferedReader br = null;
        try {
            in = url.openStream();
            reader = new InputStreamReader(in);
            br = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } finally {
            if (br != null) {
                br.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (in != null) {
                in.close();
            }
        }
    }

    public static void nullifyStrings(Object o) {

        for (Field f : o.getClass().getDeclaredFields()) {
            f.setAccessible(true);
            try {
                if (f.getType().equals(String.class)) {
                    String value = (String) f.get(o);
                    if (value != null && value.trim().isEmpty()) {
                        f.set(o, null);
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}
